package com.xinzhi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xinzhi.log.LoginLog;
import com.xinzhi.mapper.AuthCodeLoginMapper;
import com.xinzhi.pojo.User;
import com.xinzhi.service.IAuthCodeLoginService;
import com.xinzhi.service.IVerifyService;
import com.xinzhi.utils.RedisUtils;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthCodeLoginServiceImpl implements IAuthCodeLoginService {
    @Autowired
    private IVerifyService verifyService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AuthCodeLoginMapper authCodeLoginMapper;
    @Autowired
    private LoginLog loginLog;
    @Override
    public Result authCodeLogin(String phone, String authCode) {
        if (phone== null)
            return Result.error(400,"手机号不能为空");
        if (!verifyService.isValidPhoneNumber(phone))
            return Result.error(400,"手机号格式不正确");
        if (authCode == null)
            return Result.error(400,"验证码不能为空");
        if (!verifyService.isValidAuthCode(authCode))
            return Result.error(400,"验证码格式不正确");
        if (StrUtil.isBlankIfStr(redisUtils.get(phone)))
            return Result.error(400,"验证码已过期");
        if (!redisUtils.get(phone).toString().equals(authCode))
            return Result.error(400,"验证码错误");
        User u = (User) redisUtils.get("user" + phone);
        // 验证码正确，进行登录操作
        if (!StrUtil.isBlankIfStr(redisUtils.get("user"+phone))) {
            loginLog.insertLoginLog(u.getId(),1);
            return Result.ok(redisUtils.get("user" + phone));
        }
        User userByPhone = authCodeLoginMapper.getUserByPhone(phone);
        if (userByPhone == null)
            return Result.error(400,"该手机号未注册");
        loginLog.insertLoginLog(u.getId(),1);
        redisUtils.set("user"+phone,userByPhone,300);
        return Result.ok(userByPhone);
    }
}
